# -*- coding: utf-8 -*-
import string
import base64
import os
import stat
import shutil
import time
import sys
#遍历当前目录的所有文件 endStrings 后缀名的元组
def getFiles(path, intputString='输入需要加密文件的后缀名多个后缀用空格隔开 默认为.jpg .png) : '):
    fileEndString = input(intputString)
    inputEndList = fileEndString.split(" ")
    endTuple = tuple(inputEndList)
    if len(fileEndString) <= 0:
       endTuple = ('.jpg', '.png')
    if not checkEndTupleIsvaliable(endTuple):
        getFiles(path,'后缀名输入有误请重新输入:')

    curpath = path
    fileList = []
    for root, dirs,files in os.walk(curpath):
        for file in files:
            if endWith(file, endTuple):
                path = root.replace(curpath, '')
                if len(path) > 0: 
                    fileList.append(path.strip('\\') + '\\' + file)
                else:
                    fileList.append(path + file)
    
    return fileList

#检查文件file是否已endStrings为后缀
def endWith(file,endStrings):
    array = map(file.endswith,endStrings)
    if True in array:
        return True
    else:
        return False

# 检查后缀名的元组是否有效
def checkEndTupleIsvaliable(endTuple):
    for endstring in endTuple:
        if len(endstring) <= 0:
            return False
        if not endstring.startswith('.'):
            return False

    return True

# 创建目录
def createPath(path):
    if not os.path.exists(path):
            os.makedirs(path)


#filePath:文件夹路径
def delete_file(filePath):
    if os.path.exists(filePath):
        for fileList in os.walk(filePath):
            for name in fileList[2]:
                os.chmod(os.path.join(fileList[0], name), stat.S_IWRITE)
                os.remove(os.path.join(fileList[0], name))
        shutil.rmtree(filePath)

#获得当前py的目录
def getPyPath():
    return os.path.realpath(sys.argv[0])[0:os.path.realpath(sys.argv[0]).rfind('\\')]
def encodeBase64Str(baseStr):
    # print(bytes.encode(baseStr))
    byteList = list(baseStr)  # 将字符串转换成列表
    # print(l)
    indexList = []
    for index in range(1,len(byteList) + 1,1):
        if index in indexList:
            continue
        changeIndex = index * index
        if changeIndex < len(byteList):
            tempData = byteList[index]
            byteList[index] = byteList[changeIndex]
            byteList[changeIndex] = tempData
            
            indexList.append(index)
            indexList.append(changeIndex)
        else:
            break
       
    return str.encode(''.join('%c' %id for id in byteList))

if __name__ == "__main__":
    filePath = input('请输入图片所在的路径，默认为当前py文件所在目录 ')
    curpath = ''
    if len(filePath) > 0 :
        curpath = filePath
    else:
        curpath = os.getcwd()
    
    encodePath = curpath + '\\encodeData'
    delete_file(encodePath)
    createPath(encodePath)

    start_time = time.time()
    fileList = getFiles(curpath)
    for fileName in fileList:
        file = open(curpath + '\\' + fileName, 'rb')
        b64str = base64.b64encode(file.read())
        newFile = curpath + '\\encodeData\\' + fileName
        newPath = newFile[0:newFile.rfind('\\')]
        createPath(newPath)

        saveFile = os.path.splitext(newFile)[0] + '.data'
        file_object = open(saveFile, 'wb')
        file_object.write(encodeBase64Str(b64str))
        file_object.close()
        file.close()
    # 计算时间差值
    seconds, minutes, hours = int(time.time() - start_time), 0, 0
    # 可视化打印
    hours = seconds // 3600
    minutes = (seconds - hours*3600) // 60
    seconds = seconds - hours*3600 - minutes*60
    print("\n  完成耗时 {:>02d}:{:>02d}:{:>02d}".format(hours, minutes, seconds))
    pass
